package cn.ocars.playgame.pencilstudy.ui.components

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cn.ocars.playgame.pencilstudy.ui.components.RecognitionResult

/**
 * 文字识别演示界面
 * 用于测试和展示文字识别功能
 */
@Composable
fun WritingRecognitionDemo(
    modifier: Modifier = Modifier,
    onBackClick: (() -> Unit)? = null
) {
    var selectedCharacter by remember { mutableStateOf("1") }
    var scoreResult by remember { mutableStateOf<WritingScoreEvaluator.ScoreResult?>(null) }
    
    val supportedCharacters = CharacterDataProvider.getSupportedCharacters()
    
    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // 顶部导航栏
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 返回按钮
            onBackClick?.let {
                IconButton(
                    onClick = it,
                    modifier = Modifier.padding(end = 8.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.ArrowBack,
                        contentDescription = "返回",
                        tint = MaterialTheme.colorScheme.primary
                    )
                }
            }
            
            Text(
                text = "文字识别书写练习",
                fontSize = 24.sp,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.weight(1f)
            )
        }
        
        // 字符选择器
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 16.dp)
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "选择要练习的字符：",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Medium,
                    modifier = Modifier.padding(bottom = 8.dp)
                )
                
                LazyColumn(
                    modifier = Modifier.height(120.dp)
                ) {
                    items(supportedCharacters.chunked(5)) { rowCharacters ->
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            rowCharacters.forEach { character ->
                                FilterChip(
                                    onClick = { 
                                        selectedCharacter = character
                                        // 输出日志显示低延迟书写卡片组件的调用参数
                                        val characterData = CharacterDataProvider.getCharacterData(character)
                                        println("低延迟书写卡片组件调用参数:")
                                        println("  - 字符: $character")
                                        println("  - 字符类型: ${characterData?.characterType?.name ?: "未知"}")
                                        println("  - 预估笔画数: ${characterData?.getTotalStrokes() ?: "未知"}")
                                        println("  - 实际笔画数: ${characterData?.strokes?.size ?: "未知"}")
                                        println("  - 笔画详情: ${characterData?.strokes?.mapIndexed { index, stroke -> "第${index+1}笔: ${stroke.path}" }?.joinToString(", ") ?: "无"}")
                                    },
                                    label = { Text(character) },
                                    selected = selectedCharacter == character,
                                    modifier = Modifier.weight(1f)
                                )
                            }
                            // 填充剩余空间
                            repeat(5 - rowCharacters.size) {
                                Spacer(modifier = Modifier.weight(1f))
                            }
                        }
                    }
                }
            }
        }
        
        // 书写区域
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 16.dp)
        ) {
            Column(
                modifier = Modifier.padding(16.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = "书写区域 - 当前字符: $selectedCharacter",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Medium,
                    modifier = Modifier.padding(bottom = 8.dp)
                )
                
                // 获取字符类型信息
                val characterData = CharacterDataProvider.getCharacterData(selectedCharacter)
                val characterType = characterData?.characterType?.name ?: "未知"
                
                Text(
                    text = "字符类型: $characterType",
                    fontSize = 14.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(bottom = 16.dp)
                )
                
                LowLatencyWritingCard(
                    character = selectedCharacter,
                    onWritingComplete = { result ->
                        scoreResult = result
                        // 输出评分结果日志
                        println("低延迟书写卡片评分结果:")
                        println("  - 字符: $selectedCharacter")
                        println("  - 总分: ${result.totalScore}")
                        println("  - 识别结果: ${result.recognitionResult?.recognizedText ?: "无"}")
                        println("  - 识别置信度: ${result.recognitionResult?.confidence ?: 0}")
                        println("  - 反馈: ${result.feedback}")
                    },
                    modifier = Modifier.size(200.dp)
                )
            }
        }
        
        // 评分结果显示
        scoreResult?.let { result ->
            Card(
                modifier = Modifier.fillMaxWidth()
            ) {
                Column(
                    modifier = Modifier.padding(16.dp)
                ) {
                    Text(
                        text = "评分结果",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.padding(bottom = 12.dp)
                    )
                    
                    // 总分
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(bottom = 8.dp),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text("总分：")
                        Text(
                            text = "${result.totalScore.toInt()}分",
                            fontWeight = FontWeight.Bold,
                            color = when {
                                result.totalScore >= 80 -> MaterialTheme.colorScheme.primary
                                result.totalScore >= 60 -> MaterialTheme.colorScheme.tertiary
                                else -> MaterialTheme.colorScheme.error
                            }
                        )
                    }
                    
                    // 识别结果（如果有）
                    if (result.recognitionResult != null) {
                        Divider(modifier = Modifier.padding(vertical = 8.dp))
                        
                        Text(
                            text = "文字识别结果",
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Medium,
                            modifier = Modifier.padding(bottom = 8.dp)
                        )
                        
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 4.dp),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Text("识别字符：")
                            Text(
                                text = result.recognitionResult.recognizedText.ifEmpty { "未识别" },
                                fontWeight = FontWeight.Medium
                            )
                        }
                        
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 4.dp),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Text("识别置信度：")
                            Text("${(result.recognitionResult.confidence * 100).toInt()}%")
                        }
                        
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 4.dp),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Text("识别准确度：")
                            Text("${result.recognitionScore.toInt()}分")
                        }
                        
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 8.dp),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Text("书写质量：")
                            Text("${result.qualityScore.toInt()}分")
                        }
                    } else {
                        // 位置偏差评分结果
                        Divider(modifier = Modifier.padding(vertical = 8.dp))
                        
                        Text(
                            text = "位置偏差评分结果",
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Medium,
                            modifier = Modifier.padding(bottom = 8.dp)
                        )
                        
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 4.dp),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Text("重合度：")
                            Text("${result.overlapScore.toInt()}分")
                        }
                        
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 8.dp),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Text("完整度：")
                            Text("${result.completenessScore.toInt()}分")
                        }
                    }
                    
                    // 反馈信息
                    Divider(modifier = Modifier.padding(vertical = 8.dp))
                    
                    Text(
                        text = "反馈建议",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )
                    
                    Text(
                        text = result.feedback,
                        fontSize = 14.sp,
                        lineHeight = 20.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
        }
    }
}